package com.springboot.frame.wx.tools;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.springboot.fram.network.HttpUtils;
import com.springboot.frame.wx.body.resp.AccessTokenRespBody;
import com.springboot.frame.wx.body.resp.JsApiTicketRespBody;
import com.springboot.frame.wx.body.resp.UserInfoRespBody;
import com.springboot.frame.wx.config.WxConfig;
import org.apache.commons.lang3.StringUtils;
import java.text.MessageFormat;

/**
 * @author liheng
 * @ClassName FormatUrl
 * @Description
 * @date 2020-12-04 13:55
 */
public class WxResqTools {
    /**
     * AccessToken url
     * {
     * "access_token":"ACCESS_TOKEN",
     * "expires_in":7200,
     * "refresh_token":"REFRESH_TOKEN",
     * "openid":"OPENID",
     * "scope":"SCOPE"
     * }
     */
    private static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";

    /**
     * 获取用户信息
     * {
     * "subscribe": 1, 用户是否订阅该公众号标识，值为0时，代表此用户没有关注该公众号，拉取不到其余信息。
     * "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
     * "nickname": "Band",
     * "sex": 1,
     * "language": "zh_CN",
     * "city": "广州",
     * "province": "广东",
     * "country": "中国",
     * "headimgurl":"http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
     * "subscribe_time": 1382694957,
     * "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
     * "remark": "",
     * "groupid": 0,
     * "tagid_list":[128,2],
     * "subscribe_scene": "ADD_SCENE_QR_CODE",
     * "qr_scene": 98765,
     * "qr_scene_str": ""
     * }
     */
    private static String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";


    /**
     * 获取 ticket
     * {
     * "errcode":0,
     * "errmsg":"ok",
     * "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
     * "expires_in":7200
     * }
     */
    private static String JSAPI_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi";

    /**
     * @param wxConfig
     * @param code
     * @return
     */
    public static AccessTokenRespBody getAccessToken(WxConfig wxConfig, String code) {
        String requestUrl = MessageFormat.format(ACCESS_TOKEN_URL, wxConfig.getAppID(), wxConfig.getSecret(), code);
        String respBody = HttpUtils.doGet(requestUrl);
        // 判断有误异常
        JSONObject object = JSONObject.parseObject(respBody);
        String errmsg = object.getString("errmsg");
        String errcode = object.getString("errcode");
        if (StringUtils.isNoneBlank(errmsg)) {
            // 抛出错误
            throw new WxException(errcode + ":" + errmsg);
        }
        AccessTokenRespBody accessTokenRespBody = new Gson().fromJson(respBody, AccessTokenRespBody.class);
        return accessTokenRespBody;
    }

    /**
     * @param accessToken
     * @param openid
     * @return
     */
    public static UserInfoRespBody getUserInfo(String accessToken, String openid) {
        String requestUrl = MessageFormat.format(USER_INFO_URL, accessToken, openid);
        String respBody = HttpUtils.doGet(requestUrl);
        // 判断有误异常
        JSONObject object = JSONObject.parseObject(respBody);
        String errmsg = object.getString("errmsg");
        String errcode = object.getString("errcode");
        if (StringUtils.isNoneBlank(errmsg)) {
            // 抛出错误
            throw new WxException(errcode + ":" + errmsg);
        }
        UserInfoRespBody userInfoRespBody = new Gson().fromJson(respBody, UserInfoRespBody.class);
        return userInfoRespBody;
    }

    /**
     * @param accessToken
     * @return
     */
    public static JsApiTicketRespBody getJsApiTicKet(String accessToken) {
        String requestUrl = MessageFormat.format(JSAPI_TICKET_URL, accessToken);
        String respBody = HttpUtils.doGet(requestUrl);
        // 判断有误异常
        JSONObject object = JSONObject.parseObject(respBody);
        String errmsg = object.getString("errmsg");
        String errcode = object.getString("errcode");
        if (StringUtils.isNoneBlank(errcode) && !"0".equals(errcode)) {
            // 抛出错误
            throw new WxException(errcode + ":" + errmsg);
        }
        JsApiTicketRespBody jsApiTicketRespBody = new Gson().fromJson(respBody, JsApiTicketRespBody.class);
        return jsApiTicketRespBody;
    }
}
